import fetch from "isomorphic-fetch";

export const getNews = (data,ids) => {
    return {
        type:"GETNEWS",
        payload:{
            data:data,
            ids:ids
        }
    }
};
export const getGoods = (data,ids) => {
    return {
        type:"GETGOODS",
        payload:{
            data:data,
            ids:ids
        }
    }
};
export const getNewsCate = (data) => {
    return {
        type:"GETNEWSCATE",
        payload:data
    }
};
export const getCateChild = (data) => {
    return {
        type:"GETCATECHILD",
        payload:data
    }
};
export const addCart = (data) => {
    return {
        type:"ADDTOCART",
        payload:data
    }
};
export const downGoods = (data) => {
    return {
        type:"DOWN",
        payload:data
    }
};
export const upGoods = (data) => {
    return {
        type:"UP",
        payload:data
    }
};
export const delGoods = (data) => {
    return {
        type:"DELETE",
        payload:data
    }
};



export const fetchNews = (page,rows,ids,title) => {
    var id = "page="+page+"&rows="+rows;
    if(ids){
        id = id+"&_id="+ids;
    }
    if(title){
        id = id+"&title="+title;
    }
    return (path) => {
        var url = `http://127.0.0.1:3000/news/list`;
        return fetch(url,{
            method:"POST",
            body:id,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        })
        .then(response => {
            return response.json();
        }) 
        .then(data => {
            path(getNews(data,ids))
        })
    }
}
export const fetchGoods = (page,rows,ids,title) => {
    var id = "page="+page+"&rows="+rows;
    if(ids){
        id = id+"&_id="+ids;
    }
    if(title){
        id = id+"&title="+title;
    }
    return (path) => {
        var url = `http://127.0.0.1:3000/goods/list`;
        return fetch(url,{
            method:"POST",
            body:id,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        })
        .then(response => {
            return response.json();
        }) 
        .then(data => {
            path(getGoods(data,ids))
        })
    }
}
export const fetchNewsCate = (i) => {
    return (path) => {
        var url = `http://127.0.0.1:3000/cate/list/${i}`;
        return fetch(url)
        .then(response => {
            return response.json();
        }) 
        .then(data => {
            path(getNewsCate(data))
        })
    }
}
export const fetchCateChild = (id) => {
    return (path) => {
        var url = `http://127.0.0.1:3000/cate/getFamily/${id}`;
        return fetch(url)
        .then(response => {
            return response.json();
        }) 
        .then(data => {
            path(fetchNews(1,5,data));
            path(fetchGoods(1,8,data));
        })
    }
}

export const addToCart = (params) =>{
    return (dispatch) => {
        dispatch(addCart(params))
    }
}

